package com.gome.ocean.service.base;

import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.gome.ocean.common.constants.Constants;
import com.gome.ocean.common.utils.AddressUtils;
import com.gome.ocean.common.utils.ResponsePage;
import com.gome.ocean.dao.model.authority.User;
import com.gome.ocean.service.authority.ProjectService;
import com.google.common.collect.Maps;

/**
 * 基础方法
 * 
 * @author haqiaolong 2016年3月8日 下午3:31:16
 * @since 5.0.0
 */
public class BaseController {

    private static final Logger LOG                      = LoggerFactory.getLogger(BaseController.class);
    @Autowired
    protected ProjectService    projectService;
    public static final String  ERROR_MSG                = "方法执行过程中发生异常，请联系管理员";
    protected final int         DEFAULT_MAX_PROJECT_ROWS = 500;
    protected final int         DEFAULT_MIN_PROJECT_ROWS = 500;
    protected final String      FIND_NO_RESULTS          = "未查询到结果";
    protected final String      FIND_SUCCESS             = "查询成功";
    protected final String      INSERT_SUCCESS           = "插入成功";
    protected final String      INSERT_FAILURE           = "插入失败";
    protected final String      REMOVE_SUCCESS           = "删除成功";
    protected final String      REMOVE_FAILURE           = "删除失败";
    protected final String      UPDATE_SUCCESS           = "更新成功";
    protected final String      UPDATE_FAILURE           = "更新失败";
    protected final String      EXCEPTION_MSG            = "方法执行过程中发生异常，请联系维护人员";
    protected final String      NULL_PROJECT             = "您还未加入任何项目组，请联系管理员为您分配";

    protected ResponsePage getResponsePage() {
        return new ResponsePage();
    }

    /**
     * 获取HttpServletRequest
     * 
     * @return
     */
    protected HttpServletRequest getHttpRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    /**
     * 获取客户端IP地址
     * 
     * @param request
     * @return
     */
    protected String getIpAddr(HttpServletRequest request) {
        String ipAddr = request.getHeader("x-forwarded-for");
        if (StringUtils.isEmpty(ipAddr) || "unknown".equalsIgnoreCase(ipAddr)) {
            ipAddr = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ipAddr) || "unknown".equalsIgnoreCase(ipAddr)) {
            ipAddr = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isEmpty(ipAddr) || "unknown".equalsIgnoreCase(ipAddr)) {
            ipAddr = request.getRemoteAddr();
        }
        if (StringUtils.isNotEmpty(ipAddr) && ipAddr.length() > 15) {
            if (ipAddr.indexOf(",") > 0) {
                ipAddr = ipAddr.substring(0, ipAddr.indexOf(","));
            }
        }
        return ipAddr;
    }

    /**
     * 获取string参数值
     *
     * @param paramName
     * @return
     */
    protected String getParamValue(String paramName) {
        return getHttpRequest().getParameter(paramName).trim();
    }

    /**
     * 获取int参数值
     *
     * @param paramName
     * @return
     */
    protected int getIntParamValue(String paramName) {
        return Integer.parseInt(getParamValue(paramName));
    }

    /**
     * 获取Long参数值
     *
     * @param paramName
     * @return
     */
    protected long getLongParamValue(String paramName) {
        return Long.parseLong(getParamValue(paramName));
    }

    /**
     * 获取参数Map
     *
     * @return
     */
    protected Map<String, Object> getParamsMap() {
        HttpServletRequest req = getHttpRequest();
        Map<String, Object> paramsMap = Maps.newHashMap();
        Enumeration<String> enumeration = req.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String paramName = enumeration.nextElement();
            paramsMap.put(paramName, req.getParameter(paramName));
        }
        return paramsMap;
    }

    protected int getPageNumFromRequest(HttpServletRequest req) {
        int pageNum = Constants.DEFAULT_PAGE_NUM;
        String pageNumStr = req.getParameter("pageNum");
        if (StringUtils.isNotBlank(pageNumStr)) {
            pageNum = Integer.parseInt(pageNumStr);
        }
        return pageNum;
    }

    protected int getPageNum() {
        return getPageNumFromRequest(getHttpRequest());
    }

    protected int getPageSizeFromRequest(HttpServletRequest req) {
        int pageSize = Constants.DEFAULT_PAGE_SIZE;
        String pageSizeStr = req.getParameter("pageSize");
        if (StringUtils.isNotBlank(pageSizeStr)) {
            pageSize = Integer.parseInt(pageSizeStr);
        }
        return pageSize;
    }

    protected int getPageSize() {
        return getPageSizeFromRequest(getHttpRequest());
    }

    /**
     * 获取当前用户，邮件名
     * 
     * @param req
     * @return
     */
    protected String getCurrentUser(HttpServletRequest req) {
        User user = (User) req.getSession().getAttribute(Constants.SESSION_LOGIN_USER);
        return user.getEmail();
    }

    /**
     * 获取当前用户，邮箱名
     * 
     * @return
     */
    protected String getCurrentUser() {
        HttpServletRequest req = getHttpRequest();
        User user = (User) req.getSession().getAttribute(Constants.SESSION_LOGIN_USER);
        return user.getEmail();
    }

    /**
     * 获取当前用户，用户名
     * 
     * @return
     */
    protected String getCurrentUserName() {
        return getCurrentUser().split("@")[0];
    }

    /**
     * 获取当前用户对象
     * 
     * @return
     */
    protected User getCurrentUserObj() {
        HttpServletRequest req = getHttpRequest();
        User user = (User) req.getSession().getAttribute(Constants.SESSION_LOGIN_USER);
        return user;
    }

    /**
     * zhangguoqing 获取本机ip和本机名称及系统信息
     */
    protected Map<String, Object> getLocalHostIpAndNameAndSysInfo() {
        String hostIp = AddressUtils.getHostIp();
        String hostName = AddressUtils.getHostName();
        Properties properties = System.getProperties();
        Set<String> sysInfo = properties.stringPropertyNames();
        Map<String, Object> map = Maps.newHashMap();
        map.put("hostIp", hostIp);
        map.put("hostName", hostName);
        map.put("sysInfo", sysInfo);
        return map;
    }
}
